package jsp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 黄衡熙
 * @version 1.0
 */
@WebServlet("*.cookie")
public class CookieServlet extends HttpServlet {
    protected void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{
        String path = req.getServletPath();
        switch(path){
            case "/add.cookie":
                addCookie(req, resp);
                break;
            case "/find.cookie":
                findCookie(req, resp);
                break;
            case "/modify.cookie":
                modifyCookie(req, resp);
                break;
            case "/remove.cookie":
                removeCookie(req, resp);
                break;
        }
    }
    protected void addCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 在响应的同时将cookie带回到客户端
        // Cookie只能保存字符串
        Cookie cookie = new Cookie("username", "admin");
        Cookie cookie2 = new Cookie("name", "管理员");
        resp.addCookie(cookie);
        resp.addCookie(cookie2);
    }
    protected void findCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从请求中获取所携带的所有Cookie数据
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() + ":" + cookie.getValue());
        }
    }
    protected void modifyCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 在Cookie没有提供修改方法,但是在添加Cookie数据的时候,其key不能重复
        // 当key重复的时候,会进行value的覆盖
        Cookie cookie = new Cookie("username", "jack");
        resp.addCookie(cookie);
    }
    protected void removeCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 在Cookie没有提供删除方法
        // 但是可以设置cookie的生存时间
        Cookie cookie = new Cookie("username", "alice");
        // 此时表示cookie的生存时间为10秒
        // 10秒后cookie自动删除
//        cookie.setMaxAge(10);
        // 如果想要直接删除,可以设置生存时间为0秒
        cookie.setMaxAge(0);
        resp.addCookie(cookie);
    }
}
